<template>
  <van-row class="activity-home-container" type="flex">
    <!-- 顶部导航栏 -->
    <van-row id="top">
      <!-- NavBar Start -->
      <van-nav-bar class="nav-bar">
        <template #left>
          <van-row
            @click="isShowHintPopUp = true"
            class="btn-back"
            type="flex"
            justify="center"
            align="center"
          >
            <img src="@/assets/image/btn_back.png" />
          </van-row>
        </template>

        <template #right>
          <van-row
            ref="redPacketBtn"
            class="redPacket-btn"
            type="flex"
            justity="center"
            @click="goWallet"
          >
            <img class="icon-wallet" src="@/assets/image/icon_money.png" />
            <span class="money-text">{{
              user.totalMoney > 0 ? `${user.totalMoney}元` : "现金"
            }}</span>
          </van-row>
        </template>
      </van-nav-bar>
      <!-- NavBar End -->

      <!-- 广告弹窗 Start -->
      <van-overlay :show="start.window" class="pop-up-ad-mask" duration="0.1">
        <van-row class="pop-up-ad-wrap">
          <!-- 广告图片 -->
          <van-row class="pop-up-ad-img-wrap" type="flex" justify="center">
            <img src="@/assets/image/popup_ad.png" />
          </van-row>

          <!-- 立即前往按钮 -->
          <van-row class="pop-up-ad-btn-wrap" type="flex" justify="center">
            <img src="@/assets/image/btn_go.png" @click="closePopUpWindow" />
          </van-row>

          <!-- 关闭按钮 -->
          <van-row class="pop-up-ad-close-wrap" type="flex" justify="center">
            <img src="@/assets/image/btn_close.png" @click="closePopUpWindow" />
          </van-row>
        </van-row>
      </van-overlay>
      <!-- 广告弹窗 End -->

      <!-- 返回提示弹窗 Start -->
      <van-overlay :show="isShowHintPopUp" class="hint-pop-up-container">
        <van-row class="hint-pop-up-wrap">
          <!-- 背景及提示 -->
          <van-row class="hint-message-wrap" type="flex" justify="center">
            <img class="hint-bg-img" src="@/assets/image/hint_pop_up.png" />
            <p>1.21-2.20期间，每天都有三次抽卡机会，记得来抽哦</p>
            <button @click="isShowHintPopUp = false">
              <img src="@/assets/image/btn_draw.png" />
            </button>
          </van-row>

          <!-- 关闭按钮 -->
          <van-row class="hint-pop-up-close-wrap" type="flex" justify="center">
            <button @click="leaveCurrentPage">
              <span>残忍离开</span>
            </button>
          </van-row>
        </van-row>
      </van-overlay>
      <!-- 返回提示弹窗 End -->
    </van-row>

    <!-- 核心 -->
    <van-row
      id="main"
      type="flex"
      justify="center"
      align="center"
      :style="{
        visibility: isShowHintPopUp === true ? 'hidden' : 'visible',
      }"
    >
      <!-- 容器 -->
      <van-row class="main-container" type="flex" justify="center">
        <!-- 抽奖动画的卡片展示 -->

        <van-row
          class="animation-card-wrap"
          type="flex"
          justify="center"
          align="center"
        >
          <div
            ref="animationCardItem"
            class="animation-card-item"
            :class="'animation-card-item-' + (index + 1)"
            :key="index"
            v-for="(item, index) in 5"
          >
            <img src="@/assets/image/home_card.png" />
          </div>
        </van-row>
        <!-- 开始抽奖按钮 -->
        <van-row class="start-lottery-wrap" type="flex" justify="center">
          <button @click="startLottery" :disabled="isDisabled">
            <img src="@/assets/image/btn_tack.png" />
            <span>马上抽卡X{{ user.count }}</span>
          </button>
        </van-row>

        <!-- 分享好友 -->
        <van-row class="share-firend-get-count">
          <button @click="shareClick">
            <img src="@/assets/image/icon_WeChat.png" />
            <span>分享好友，免费得抽奖机会</span>
          </button>
        </van-row>
      </van-row>

      <!-- 中奖弹窗 -->
      <van-popup
        v-model="popup.isShow"
        class="winning-pop-up-mask"
        duration="0.1"
        @closed="closeWinningOverlay"
      >
        <van-row class="winning-pop-up-wrap">
          <!-- 红包内容 -->
          <WinningRedPacket
            v-if="activeType === REDPACKET"
            :money="result.toFixed(2)"
            :isAccept="isAccept"
            :left="redPacketPosition.left"
            :top="redPacketPosition.top"
            @inviteFriendDrawCard="inviteFriendDrawCard"
            @acceptRedPacket="acceptRedPacket"
            @redPacketTransitionEnd="redPacketTransitionEnd"
          />

          <!-- 卡片内容 -->
          <WinningCard
            v-if="activeType === CARD"
            :currentCard="result"
            :isAccept="isAccept"
            :left="cardItemOffset[showCardItemIndex].left"
            :top="cardItemOffset[showCardItemIndex].top"
            :index="showCardItemIndex"
            @inviteFriendDrawCard="inviteFriendDrawCard"
            @acceptCard="acceptCard"
            @cardTransitionEnd="cardTransitionEnd"
          />

          <!-- 无次数内容 -->
          <NoCount
            v-if="activeType === NOCOUNT"
            :showType="activeType"
            @shareClick="shareClick"
          />

          <!-- 关闭弹窗按钮 -->
          <van-row
            class="winning-pop-up-close-btn"
            type="flex"
            justify="center"
            :style="{ visibility: !isAccept ? 'hidden' : 'visible' }"
          >
            <button class="close-btn" @click="closeWinningWindow">
              <img src="@/assets/image/btn_close.png" />
            </button>
          </van-row>
        </van-row>
      </van-popup>
    </van-row>

    <!-- 底部卡片展示 -->
    <van-row id="footer" type="flex" justify="space-around" align="center">
      <CardItem
        :count="item.count"
        :index="index"
        :key="item.id"
        v-for="(item, index) in user.cardList"
        class="card-item"
        :style="{
          background:
            item.count >= 1
              ? 'url(' +
                require('../assets/image/default_card_' + item.name + '.png') +
                ') no-repeat center/ contain '
              : 'url(' +
                require('../assets/image/dark_card_' + item.name + '.png') +
                ') no-repeat center/ contain ',
        }"
        @getCardItemPosition="getCardItemPosition"
        @goCardDetail="goCardDetail"
      />
    </van-row>
  </van-row>
</template>

<script>
import CardItem from "@/components/CardItem";
import WinningCard from "@/components/WinningCard";
import WinningRedPacket from "@/components/WinningRedPacket";
import NoCount from "@/components/NoCount";

import { mapGetters, mapMutations } from "vuex";

// 类型常量 显示类型：
const NORMAL = "normal"; // 正常（无弹框）
const CARD = "card"; //卡片
const REDPACKET = "redPacket"; //红包
const NOCOUNT = "noCount"; //无次数弹框
const WINNINGINFO = [0, "牛", "气", "冲", ["牛", "气", "冲"]]; // 可中奖列表 0：随机0.xx

// 假数据
const popup = {
  isShow: false, // 是否显示弹框
  activeType: NORMAL, //当前类型
};
const circle = {
  count: Math.floor(Math.random() * 20) < 10 ? +15 : +10, // 随机转count圈
  currentCount: 1, //当前所转圈数
  // 条件 ： 当currentCount === count  才会停止
};
let step = 0.1; // 抽奖旋转速度
const redPacketPosition = { top: 0, left: 0 };
export default {
  name: "ActivityHome",
  components: {
    CardItem,
    NoCount,
    WinningCard,
    WinningRedPacket,
  },
  props: {},
  data() {
    return {
      NORMAL,
      CARD,
      REDPACKET,
      NOCOUNT,
      WINNINGINFO,

      popup,
      circle,
      step,
      redPacketPosition, // 钱包按钮位置

      cardItemOffset: [], // 底部所有卡片的offset距离
      userWinningList: [], //记录用户中奖信息
      showCardItemIndex: null, // 当前弹框卡片对应索引
      result: null, // 中奖结果

      isShowHintPopUp: false, //控制返回提示弹框
      isDisabled: false, // 是否禁用抽奖按钮
      isAccept: true,
    };
  },
  computed: {
    activeType() {
      return this.popup.activeType;
    },
    isShow() {
      return this.popup.isShow;
    },

    ...mapGetters("activity", {
      user: "user",
      start: "start",
    }),
  },
  watch: {
    // 关闭添加奖励
    isShow() {
      if (
        (this.activeType === CARD || this.activeType === REDPACKET) &&
        this.isShow == false
      )
        this.userWinningList.push(this.result);

      if (this.stopAdd) return;
      if (
        (this.activeType === CARD || this.activeType === REDPACKET) &&
        this.isShow == false
      ) {
        if (this.activeType === CARD) this.setAddUserCount(this.result);
        if (this.activeType === REDPACKET) {
          this.setUserTotalMoney(this.result.toFixed(2));
        }
      }
    },
  },
  created() {},
  mounted() {
    this.initUser(); // 初始化用户
    // 获取距离
    this.redPacketPosition.left =
      this.$refs.redPacketBtn.$el.clientWidth / 2 +
      this.getRedPacketBtnOffsetLeft(this.$refs.redPacketBtn.$el);
    this.redPacketPosition.top =
      this.$refs.redPacketBtn.$el.clientHeight / 2 +
      this.getRedPacketBtnOffsetTop(this.$refs.redPacketBtn.$el) +
      39.86;

    // 得到卡片类型
    this.cardList = this.user.cardList.map((item) => item.category);
    //用户id
    getUserId();
  },
  methods: {
        //获取到用户唯一id
    getUserId() {
      //调用接口
      this.user.id = Math.random();
      if (!localStorage.getItem("isNewUser")) {
        //给服务器返回这个id号,看服务器返回的是新用户旧用户
        localStorage.setItem("isNewUser", isNewUser);
      }
      this.user.isNewUser = localStorage.getItem("isNewUser");
    },
    initUser() {
      if (this.user.count === null) {
        if (this.user.isNewUser === true) this.setUserCount(5);
        else this.setUserCount(3);
      }
    },
    // 开始抽奖
    startLottery() {
      if (this.isDisabled === true) return;
      const transitionDOM = this.$refs.animationCardItem[0];
      transitionDOM.addEventListener("transitionend", this.transitionend);
      // 无抽奖次数
      if (this.user.count <= 0) {
        this.popup.isShow = true; //显示弹框
        this.popup.activeType = NOCOUNT; //弹框类型 无次数弹框
        return;
      }

      // 有抽奖次数 开始抽奖
      this.setUserCount(this.user.count - 1);
      this.lotteryAnimation();
      this.isDisabled = true;
    },

    // 抽奖旋转动画
    lotteryAnimation() {
      const domArr = this.$refs.animationCardItem;
      const arr = [];
      // 获取属性
      for (let i = 0; i < domArr.length; i++) {
        const cssDescription = window.getComputedStyle(domArr[i], null);
        const cssValue = cssDescription.getPropertyValue("transform");
        domArr[i].style.transition = `transform ${this.step}s`;
        arr.push(cssValue);
      }
      // 记录位置
      for (let i = 0; i < domArr.length; i++) {
        switch (i) {
          case 0:
            domArr[i].style.transform = arr[domArr.length - 1];
            break;
          case 1:
            domArr[i].style.transform = arr[i - 1];
            break;
          case 2:
            domArr[i].style.transform = arr[i - 1];
            break;
          case 3:
            domArr[i].style.transform = arr[i - 1];
            break;
          case 4:
            domArr[i].style.transform = arr[i - 1];
            break;
        }
      }
    },

    // 抽奖旋转动画过渡完成
    transitionend() {
      this.circle.currentCount++;
      if (this.circle.currentCount < this.circle.count) this.lotteryAnimation();
      if (this.circle.currentCount === this.circle.count) {
        let res = null;

        // 获取旋转卡牌  重新设置透明度

        const domArr = this.$refs.animationCardItem;
        for (let i = 0; i < domArr.length; i++) {
          const cssDescription = window.getComputedStyle(domArr[i], null);
          const cssValue = cssDescription.getPropertyValue("transform");
          if (cssValue === "matrix(1, 0, 0, 1, 0, 0)") {
            for (let j = 0; j < domArr.length; j++) {
              domArr[j].style.opacity = "0.8";
            }
            domArr[i].style.opacity = "1";
            break;
          }
        }

        // 展示中奖结果
        setTimeout(() => {
          this.isDisabled = false;
          this.circle.currentCount = 0;

          //随机选择类型 0-4
          res = WINNINGINFO[Math.floor(Math.random() * WINNINGINFO.length)];

          //  number  string  object
          if (typeof res === "number") {
            this.popup.activeType = REDPACKET;
            if (this.user.bigPrize === true) {
              res = this.newUserBigPrizeRandomPacket();
              this.setBigPrize();
            } else {
              res = this.oldUserRandomRedPacket();
            }
          }
          if (typeof res === "string") this.popup.activeType = CARD;
          if (typeof res === "object") {
            // res  = ["牛", "气", "冲"]
            res = res[Math.floor(Math.random() * res.length)];
            this.popup.activeType = CARD;
          }

          // 前三必中
          if (this.userWinningList.length === 2) {
            // 当有数据 就判断
            const privateRes = this.userWinningList.some((item) => {
              return typeof item === "number" && item >= 1;
            });
            if (privateRes === false && this.user.bigPrize === true) {
              res = this.newUserBigPrizeRandomPacket();
              this.popup.activeType = REDPACKET;
              this.setBigPrize();
            }
          }
          // 调整奖励
          switch (this.popup.activeType) {
            case REDPACKET:
              console.log("进入REDPACKET");
              // 0.xx || 1.0x
              this.result = res;
              break;
            case CARD:
              console.log("进入CARD");
              this.result = res;

              const arr = this.user.cardList.filter((item) => {
                return item.category == this.result;
              });
              this.showCardItemIndex = arr.length >= 1 ? arr[0].id : null;
              break;
          }

          // 显示中奖信息
          this.popup.isShow = true;
          this.accept = true;
        }, 200);
      }
    },

    // 获取卡片的offset距离
    getCardItemPosition(v) {
      this.cardItemOffset.push(v);
    },
    // 点击收纳卡片
    acceptCard() {
      this.isAccept = false;
    },
    // 收纳卡片动画结束
    cardTransitionEnd() {
      this.popup.isShow = false;
    },
    // 点击收纳红包
    acceptRedPacket() {
      this.isAccept = false;
    },
    // 收纳红包动画结束
    redPacketTransitionEnd() {
      this.popup.isShow = false;
    },
    // 获得钱包按钮的位置
    getRedPacketBtnOffsetLeft(el) {
      return (
        el.offsetLeft +
        (el.offsetParent ? this.getRedPacketBtnOffsetLeft(el.offsetParent) : 0)
      );
    },
    getRedPacketBtnOffsetTop(el) {
      return (
        el.offsetTop +
        (+el.offsetParent ? this.getRedPacketBtnOffsetTop(el.offsetParent) : 0)
      );
    },

    // 去钱包页面
    goWallet() {
      if (
        this.circle.currentCount > 1 &&
        this.circle.currentCount !== this.circle.count
      ) {
        this.stopSkip();
        return;
      }
      this.$router.push("/wallet");
    },
    // 去卡片详情
    goCardDetail(index) {
      if (
        this.circle.currentCount > 1 &&
        this.circle.currentCount !== this.circle.count
      ) {
        this.stopSkip();
        return;
      }
      this.$router.push("/cardDetail");
      this.setDetailIndex(index);
    },
    // 阻止跳转其他页面 提示
    stopSkip() {
      this.$notify({
        type: "warning",
        message: "当前正在抽奖,请勿操作其他",
        className: "notify",
        duration: "800",
      });
    },

    // 离开当前页面
    leaveCurrentPage() {
      this.isShowHintPopUp = false;
      this.$router.back(-1);
    },

    // 送好友卡片（中奖信息弹框）
    inviteFriendDrawCard() {
      this.popup.isShow = false;
      alert("邀请好友抽卡操作");
    },

    // 关闭广告提示框
    closePopUpWindow() {
      // 页面加载 进行抽奖
      if (this.user.count >= 1 && this.start.page === true) {
        this.startLottery();
        this.setStartPage(false);
      }
      this.setStartWindow(false);
    },

    // 手动点击关闭中奖窗口
    closeWinningWindow() {
      this.popup.isShow = false;
    },

    //  三方API
    closeWinningOverlay() {
      this.popup.activeType = NORMAL;
      this.isAccept = true;
      this.$refs.animationCardItem[0].removeEventListener(
        "trnasitionend",
        this.transitionend
      );
    },

    // 生成0.xx
    oldUserRandomRedPacket() {
      return parseFloat(
        `0.${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}`
      );
    },

    // 生成1.0x
    newUserBigPrizeRandomPacket() {
      return parseFloat(`1.0${Math.floor(Math.random() * 10)}`);
    },

    // 微信分享得次数
    shareClick() {
      const res = prompt("请根据右边好友列表，进行分享[q,w,e,a,s,d]");

      if (res === null) {
        alert("取消分享操作");
        this.popup.isShow = false;
        return;
      }
      // 好友不存在
      if (
        res === "q" ||
        res === "w" ||
        res === "e" ||
        res === "a" ||
        res === "s" ||
        res === "d"
      ) {
        // 好友存在
        const isSend = confirm("确定要分享给该好友吗？");
        if (isSend) {
          this.setUserCount(this.user.count + 1);
        } else {
          alert("取消分享");
        }
      } else {
        alert("该好友不存在,分享失败");
      }
      this.popup.isShow = false;
    },

    ...mapMutations("activity", {
      setStartPage: "setStartPage",
      setStartWindow: "setStartWindow",
      setUserCount: "setUserCount",
      setBigPrize: "setBigPrize",
      setAddUserCount: "setAddUserCount",
      setUserTotalMoney: "setUserTotalMoney",
      setDetailIndex: "setDetailIndex",
    }),
  },
};
</script>

<style scoped lang='less'>
.activity-home-container {
  flex-direction: column;
  height: 100%;
  background: url("~@/assets/image/bottom_cloud.png") no-repeat bottom/contain,
    url("~@/assets/image/home_bg.png") no-repeat top/cover;
}

.activity-home-container #top {
  width: 100%;
  background: url("~@/assets/image/img_heading.png") no-repeat bottom/70%;
  // 导航栏
  /deep/.nav-bar {
    height: 138px;
    background: transparent;
    &::after {
      content: none;
    }
    .van-nav-bar__left,
    .van-nav-bar__right {
      top: 39.86px;
    }
    // 返回按钮
    .btn-back {
      img {
        width: 12px;
        height: 20px;
      }
    }
    // 进入钱包按钮
    .redPacket-btn {
      width: 65px;
      height: 19px;
      border-radius: 10px;

      display: flex;
      justify-content: space-evenly;
      align-items: center;
      background: rgba(255, 255, 255, 0.6);
      img {
        width: 19px;
        height: 19px;
      }
      span {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #fefffe;
        line-height: 19px;
      }
    }
  }

  // 弹窗广告
  /deep/.pop-up-ad-mask {
    display: flex;
    justify-content: center;
    align-items: center;
    .pop-up-ad-wrap {
      // 广告图片
      .pop-up-ad-img-wrap {
        img {
          width: 319px;
          height: 327px;
        }
      }

      // 前往按钮
      .pop-up-ad-btn-wrap {
        position: relative;
        top: -15px;
        img {
          width: 180px;
          height: 44px;
        }
      }

      // 关闭按钮
      .pop-up-ad-close-wrap {
        margin: 20px 0 0 0;
        img {
          width: 35px;
          height: 35px;
        }
      }
    }
  }

  // 返回弹窗
  /deep/.hint-pop-up-container {
    display: flex;
    justify-content: center;
    align-items: center;
    .hint-pop-up-wrap {
      .hint-message-wrap {
        position: relative;

        img.hint-bg-img {
          width: 321px;
          height: 308px;
        }
        p {
          position: absolute;
          top: 45%;
          width: 181px;
          height: 70px;
          text-align: center;
          font-size: 17px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #d23f3f;
          line-height: 23px;
        }
        button {
          position: absolute;
          bottom: 0;
          width: 158px;
          height: 55px;
        }
      }
      .hint-pop-up-close-wrap {
        margin: 30px 0 0 0;
        button {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 116px;
          height: 33px;
          border-radius: 17px;
          border: 1px solid #ffffff;

          span {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #ffffff;
          }
        }
      }
    }
  }
}

.activity-home-container #main {
  flex: 1;
  // 活动主页显示内容
  .main-container {
    flex-direction: column;
    width: 100%;
    height: 100%;
    // 抽奖旋转卡片
    .animation-card-wrap {
      position: relative;
      left: 50%;
      width: 50%;
      height: 60%;
      transform: translateX(-50%);
      perspective: 500px;
      transform-style: preserve-3d;

      &::before {
        content: "";
        position: absolute;
        z-index: -1;
        left: 50%;
        bottom: -55px;
        width: 330px;
        height: 88px;
        background: url("~@/assets/image/bottom_circle.png") no-repeat
          bottom/contain;
        transform: translate3d(-50%, 0, -105px) scale(1.2);
      }
      .animation-card-item {
        position: absolute;
        height: 100%;
        img {
          width: auto;
          height: 100%;
        }
        &-1 {
          transform: translate3d(0, 0, 0);
        }
        &-2 {
          transform: translate3d(30px, 0, -50px);
          opacity: 0.8;
        }
        &-3 {
          transform: translate3d(60px, 0, -100px);
          opacity: 0.8;
        }
        &-4 {
          transform: translate3d(-60px, 0, -100px);
          opacity: 0.8;
        }
        &-5 {
          transform: translate3d(-30px, 0, -50px);
          opacity: 0.8;
        }
      }
    }

    //  开始抽奖按钮
    .start-lottery-wrap {
      button {
        position: relative;
        img {
          width: 205px;
        }
        span {
          position: absolute;
          top: 10%;
          left: 50%;
          width: fit-content;
          transform: translateX(-50%);
          font-size: 22px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #fff1df;
          line-height: 32px;
          text-shadow: 0px 1px 2px #b91e2e;
        }
      }
    }

    // 分享好友得抽奖机会按钮
    .share-firend-get-count {
      button {
        display: flex;
        justify-content: space-around;
        align-items: center;
        width: fit-content;
        height: 25px;
        border-radius: 12px;
        opacity: 0.9;
        border: 1px solid #ffffff;
        img {
          width: 18px;
          height: 15px;
          margin: 0 5px 0 0px;
        }
        span {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ffffff;
          line-height: 16px;
        }
      }
    }
  }

  // 中奖遮罩层
  /deep/.winning-pop-up-mask {
    // 导航栏
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: transparent;
    .winning-pop-up-wrap {
      // 关闭中奖弹窗按钮
      .winning-pop-up-close-btn {
        margin: 30px 0 0 0;
        button {
          display: flex;
          align-items: center;
          img {
            width: 35px;
            height: 35px;
          }
        }
      }
    }
  }
}

.activity-home-container #footer {
  width: 100%;
  padding: 0 20px;
  // 导航栏
  height: 100px;
  .card-item {
    width: 60px;
    height: 80px;
  }
}
</style>